<template>
    <view class="add-form-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header
            :title="isEdit ? '编辑灌排记录' : '新增灌排记录'"
        ></page-header>

        <!-- 灌排类型选择 -->
        <view class="basic-info">
            <view class="section-title">灌排类型</view>
            <view class="form-two-columns">
                <view
                    class="type-button half"
                    :class="{ active: formData.operationType === '1' }"
                    @click="formData.operationType = '1'"
                >
                    灌溉
                </view>
                <view
                    class="type-button half"
                    :class="{ active: formData.operationType === '2' }"
                    @click="formData.operationType = '2'"
                >
                    排水
                </view>
            </view>
        </view>

        <!-- 使用地块选择器组件 -->
        <land-selector
            ref="landSelector"
            @selection-change="handleLandSelectionChange"
        ></land-selector>

        <!-- 使用条田选择器组件 -->
        <section-selector
            ref="sectionSelector"
            @areaChange="handleAreaChange"
            @usersChange="handleUsersChange"></section-selector>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form"
            >
                <uni-forms-item label="灌排时间" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="formData.dateRange"
                        :border="false"
                        :label-width="200"
                        @change="dateRangeChange"
                    >
                        <view class="uni-date-picker-container">
                            <text
                                :class="{
                                    placeholder: !formData.dateRangeText,
                                }"
                                >{{
                                    formData.dateRangeText || "请选择灌排时间"
                                }}</text
                            >
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"
                                ></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item label="灌排面积" name="area" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.area"
                        placeholder="请输入"
                        disabled
                    >
                        <template #right>
                            <text class="input-unit">亩</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="personInCharge">
                    <uni-easyinput
                        v-model="formData.personInCharge"
                        placeholder="请输入负责人姓名"
                        disabled></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="备注说明" name="remark">
                    <uni-easyinput
                        v-model="formData.remark"
                        type="textarea"
                        placeholder="请输入备注说明"
                        maxlength="100"
                    ></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>

            <image-uploader
                ref="imageUploader"
                :images="formData.images"
                :maxCount="9"
            />
        </view>

        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">{{
                isEdit ? "保存修改" : "点击上传"
            }}</view>
        </view>
    </view>
</template>

<script>
import PageHeader from "@/components/PageHeader/index.vue";
import LandSelector from "@/components/LandSelector/index.vue";
import SectionSelector from "@/components/SectionSelector/index.vue";
import ImageUploader from "@/components/ImageUploader/index.vue";
import { irrigation } from "@/utils/api/index.js";
import { formatDate, getDefaultDateRange } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        LandSelector,
        SectionSelector,
        ImageUploader,
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
            userInfo: 'getUserInfo',
        }),
    },
    data() {
        const defaultDateRange = getDefaultDateRange()
        return {
            isEdit: false,
            editId: null,
            formData: {
                operationType: '1', // '1': 灌溉, '2': 排水
                dateRange: defaultDateRange.dateRange,
                dateRangeText: defaultDateRange.dateRangeText,
                area: '',
                personInCharge: '',
                personInId: '',
                notes: '',
                images: [],
                remark: '',
            },
            rules: {
                dateRange: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择灌排时间",
                        },
                    ],
                },
                area: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请输入灌排面积",
                        },
                        {
                            format: "number",
                            errorMessage: "请输入有效的数字",
                        },
                    ],
                },
            },
            selectedLands: [],
            selectedSections: [],
        };
    },
    onLoad(options) {
        if (options.type && options.type === 'drainage') {
            this.formData.operationType = '2'
        }

        if (options.id) {
            this.isEdit = true
            this.editId = parseInt(options.id)
            this.loadRecordData(this.editId)
        } else {
            // 设置默认的负责人和负责人ID
            console.log('用户信息', this.userInfo)
            this.formData.personInId = this.userInfo.id
            this.formData.personInCharge = this.userInfo.nickname
        }
    },
    methods: {
        formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, "0");
            const day = date.getDate().toString().padStart(2, "0");
            return `${year}-${month}-${day}`;
        },

        dateRangeChange(e) {
            if (e && e.length === 2) {
                const startDate = new Date(e[0]);
                const endDate = new Date(e[1]);
                this.formData.dateRangeText = `${this.formatDate(
                    startDate
                )} 至 ${this.formatDate(endDate)}`;
            } else {
                this.formData.dateRangeText = "";
            }
        },

        // 更新地块选择回调
        handleLandSelectionChange() {
            this.updateSelectedLands();
        },
        handleAreaChange(area) {
            this.formData.area = area;
        },

        handleUsersChange(users) {
            this.formData.personInId = users.map((item) => item.userId).join(',');
            this.formData.personInCharge = users.map((item) => item.userName).join(',');
        },

        // 更新选中的地块数据
        updateSelectedLands() {
            if (this.$refs.landSelector) {
                this.selectedLands = this.$refs.landSelector.getSelectedLands();
                console.log("更新选中的地块:", this.selectedLands);

                // 当地块选择变化时，更新条田选择器
                if (this.$refs.sectionSelector) {
                    this.$refs.sectionSelector.setSelectedParcels(
                        this.selectedLands
                    );
                    // 更新选中的条田
                    this.updateSelectedSections();
                }
            }
        },

        // 更新选中的条田数据
        updateSelectedSections() {
            if (this.$refs.sectionSelector) {
                this.selectedSections =
                    this.$refs.sectionSelector.getSelectedSections();
                console.log("更新选中的条田:", this.selectedSections);
            }
        },

        // 格式化图片字段，将字符串转为数组
        formatImages(images) {
            if (!images) return [];
            if (typeof images === "string") {
                if (images.includes(",")) {
                    return images.split(",");
                }
                return [images];
            }
            return Array.isArray(images) ? images : [];
        },

        async loadRecordData(id) {
            try {
                uni.showLoading({ title: "加载中..." });

                // 调用API获取灌排记录详情
                const res = await irrigation.getIrrigationDrainageDetail(id);

                if (res.code === 0 && res.data) {
                    const recordData = res.data;

                    // 设置日期范围
                    let startDate, endDate;
                    if (recordData.startDate) {
                        startDate = new Date(recordData.startDate);
                        endDate = recordData.endDate
                            ? new Date(recordData.endDate)
                            : new Date(recordData.startDate);
                    } else {
                        startDate = new Date(recordData.createTime);
                        endDate = new Date(recordData.createTime);
                    }

                    this.formData = {
                        operationType: recordData.operationType || '1',
                        dateRange: [
                            startDate.toISOString().split('T')[0],
                            endDate.toISOString().split('T')[0],
                        ],
                        dateRangeText: `${this.formatDate(startDate)} 至 ${this.formatDate(endDate)}`,
                        area: recordData.area ? recordData.area.toString() : '',
                        personInCharge: recordData.personInCharge || '',
                        personInId: recordData.personInId || '',
                        remark: recordData.remark || '',
                        images: this.formatImages(recordData.images),
                    }

                    // 等待组件加载完成后，设置地块选择状态
                    this.$nextTick(() => {
                        // 确保组件已完全加载
                        setTimeout(() => {
                            // 设置地块选择器中选中的地块
                            if (this.$refs.landSelector && recordData.plotId) {
                                this.$refs.landSelector.setSelectedLands(
                                    recordData.plotId
                                );
                                this.updateSelectedLands();

                                // 更新条田选择器的地块ID
                                if (this.$refs.sectionSelector) {
                                    this.$refs.sectionSelector.setSelectedParcels(
                                        this.selectedLands
                                    );

                                    // 设置条田选择状态
                                    if (recordData.fieldId) {
                                        this.$refs.sectionSelector.setSelectedFields(
                                            recordData.fieldId
                                        );
                                        this.updateSelectedSections();
                                    }
                                }
                            }
                        }, 800);
                    });
                } else {
                    uni.showToast({
                        title: "获取数据失败",
                        icon: "none",
                    });
                }
                uni.hideLoading();
            } catch (error) {
                console.error("加载数据失败:", error);
                uni.hideLoading();
                uni.showToast({
                    title: "加载数据失败",
                    icon: "none",
                });
            }
        },

        validateForm() {
            // 更新选中的地块和条田
            this.updateSelectedLands();
            this.updateSelectedSections();

            // 检查是否选择了地块
            if (!this.$refs.landSelector.validate()) {
                uni.showToast({
                    title: "请选择至少一个地块",
                    icon: "none",
                });
                return false;
            }

            // 检查是否选择了条田
            if (!this.$refs.sectionSelector.validate()) {
                uni.showToast({
                    title: "请选择至少一个条田",
                    icon: "none",
                });
                return false;
            }

            return true;
        },

        submitForm() {
            // 使用uni-forms的验证方法
            this.$refs.form
                .validate()
                .then((result) => {
                    if (this.validateForm()) {
                        this.submitFormData();
                    }
                })
                .catch((errors) => {
                    console.log("表单错误信息：", errors);
                });
        },

        async submitFormData() {
            try {
                // 获取选中的地块和条田
                this.updateSelectedLands();
                this.updateSelectedSections();

                let plotId = this.selectedLands.map((item) => item.id);
                let fieldId = this.selectedSections.map((item) => item.id);

                let plotName = this.selectedLands.map((item) => item.name);
                let fieldName = this.selectedSections.map((item) => item.name);

                // 从imageUploader组件获取最新的图片列表
                const imageList = this.$refs.imageUploader.getImageList();

                // 构建提交的数据对象
                const submitData = {
                    id: this.isEdit ? this.editId : undefined,
                    operationType: this.formData.operationType,
                    startDate: this.formData.dateRange[0],
                    endDate: this.formData.dateRange[1],
                    plotId: plotId.join(","),
                    fieldId: fieldId.join(","),
                    plotName: plotName.join(","),
                    fieldName: fieldName.join(","),
                    area: parseFloat(this.formData.area),
                    personInCharge: this.formData.personInCharge,
                    images: imageList.join(","),
                    remark: this.formData.remark,
                };

                uni.showLoading({
                    title: "提交中...",
                });

                // 调用API创建或更新灌排记录
                let res;
                if (this.isEdit) {
                    res = await irrigation.updateIrrigationDrainage(submitData);
                } else {
                    res = await irrigation.createIrrigationDrainage(submitData);
                }

                uni.hideLoading();

                if (res.code === 0) {
                    uni.showToast({
                        title: this.isEdit ? "修改成功" : "添加成功",
                        icon: "success",
                        duration: 2000,
                        success: () => {
                            setTimeout(() => {
                                // 返回上一页并刷新
                                uni.navigateBack({
                                    delta: 1,
                                });
                            }, 1500);
                        },
                    });
                } else {
                    uni.showToast({
                        title: res.msg || "操作失败",
                        icon: "none",
                        duration: 2000,
                    });
                }
            } catch (error) {
                uni.hideLoading();
                console.error("提交数据失败:", error);
                uni.showToast({
                    title: "提交失败，请重试",
                    icon: "none",
                    duration: 2000,
                });
            }
        },
    },
};
</script>

<style lang="scss">
.type-button {
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #333;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    margin: 0 10rpx;

    &.active {
        background-color: #2e6140;
        color: #fff;
    }

    &:first-child {
        margin-left: 0;
    }

    &:last-child {
        margin-right: 0;
    }
}
</style>
